﻿var obj;

$(document).ready(function () {
    layui.use('form', function () {
        form = layui.form();
    });
    //iframe自适应
    $(window).on('resize', function () {
        var wh = $(this).height() - 190;
        $("iframe").each(function () {
            $(this).contents().find("#iframe").height(wh);
        });
    }).resize();
});

var Ajax = {
    Get: function (url, func) {
        return $.get(encodeURI(url), func);
    },
    Post: function (url, data, func) {
        data.sign = GetSign(data.act);
        return $.post(url, data, func);
    },
    Post2: function (url, data, func) {
        return $.ajax({
            url: url,
            type: 'GET', //GET
            async: true,    //或false,是否异步
            data: data,
            timeout: 5000,    //超时时间
            dataType: 'text',    //返回的数据格式：json/xml/html/script/jsonp/text
            success: function (data, textStatus, jqXHR) {
                func(data);
            }

        });
    }
};


var LayerBox = {
    Show: function (title, html, width, height, verify, callback) {
        return window.parent.layer.open({
            type: 1,
            title: title,
            content: html,
            btn: ['提交', '取消'],
            shade: 0.3,
            area: [width + 'px', height + 'px'],
            zIndex: 999,
            maxmin: true,
            yes: function (index) {
                //触发表单的提交事件
                $('form.layui-form').find('a[lay-filter=save]').click();
            },
            success: function (layero, index) {
                //弹出窗口成功后渲染表单
                var form = layui.form();
                form.render();
                if (verify) {
                    verify(form);
                }
                form.on('submit(save)', function (data) {
                    callback(data.field);
                });

            }
        });
    },
    Show2: function (title, html, width, height, verify, callback) {
        return layer.open({
            type: 1,
            title: title,
            content: html,
            btn: ['提交', '取消'],
            shade: 0.3,
            area: [width + 'px', height + 'px'],
            zIndex: 999,
            maxmin: true,
            yes: function (index) {
                //触发表单的提交事件
                $('form.layui-form').find('a[lay-filter=save]').click();
            },
            success: function (layero, index) {
                //弹出窗口成功后渲染表单
                var form = layui.form();
                form.render();
                if (verify) {
                    verify(form);
                }
                form.on('submit(save)', function (data) {
                    callback(data.field);
                });

            }
        });
    },
    Search: function (title, html, width, height) {

        return window.parent.layer.open({
            type: 1,
            title: title,
            content: html,
            shade: 0.3,
            area: [width + 'px', height + 'px'],
            zIndex: 999,
            maxmin: true,
            yes: function (index) {
                //触发表单的提交事件
                $('form.layui-form').find('a[lay-filter=save]').click();
            },
            success: function (layero, index) {
            }
        });
    },
    Detail: function (title, html, width, height) {
        if (width == 0 && height == 0) {
            width = "100%";
            height = "100%";
        } else {
            width = width + "px";
            height = height + "px";
        }
        return layer.open({
            type: 1,
            title: title,
            content: html,
            shade: 0.3,
            area: [width, height],
            zIndex: 999,
            maxmin: false,
            yes: function (index) {
                //触发表单的提交事件
                $('form.layui-form').find('a[lay-filter=save]').click();
            },
            success: function (layero, index) {
                var form = layui.form();
                form.render();
            }
        });
    },
    Dialog: function (title, html, width, height, callback) {
        return window.parent.layer.open({
            type: 1,
            title: title,
            content: html,
            btn: ['确定', '取消'],
            shade: 0.3,
            area: [width + 'px', height + 'px'],
            zIndex: 999,
            maxmin: true,
            yes: function (index) {
                //触发表单的提交事件
                $('form.layui-form').find('a[lay-filter=show]').click();
            },
            success: function (layero, index) {
                //弹出窗口成功后渲染表单
                var form = layui.form();
                form.render();
                form.on('submit(show)', function (data) {
                    callback(data.field);
                });

            }
        });
    },
    IFrame: function (title, url, width, height) {
       return layer.open({
            type: 2,
            title: title,
            shade: 0.3,
            area: [width, height],
            content: url //iframe的url
        });
    },
    Msg: function (msg, time) {
        if (!time) {
            time = 0;
        }
        return window.parent.layer.msg(msg, { time: time });
    },
    Loading: function () {
        return window.parent.layer.load(1, {
            shade: [0.2, '#000'] //0.1透明度的白色背景
        });
    },
    Load: function () {
        return window.parent.layer.load(1,{shade: false});
    },
    Confirm: function (msg, callback) {
        window.parent.layer.confirm(msg, { icon: 3, title: '提示' }, function (index) {
            callback();
            window.parent.layer.close(index);
        });
    },
    Prompt: function (msg, callback) {
        window.parent.layer.prompt({ title: msg, formType: 2 }, function (text, index) {
            callback(text);
            window.parent.layer.close(index);
        });
    },
    ErrorTip: function (msg, time) {
        if (!time) {
            time = 0;
        }
        return window.parent.layer.msg(msg, { icon: 2 }, function () { });
    },
    Success: function (msg, time, fun) {
        if (!time) {
            time = 1000;
        }
        return window.parent.layer.msg(msg, { time: time, icon: 1 }, fun);
    },
    Error: function (msg, time) {
        if (!time) {
            time = 1000;
        }
        return window.parent.layer.msg(msg, { time: time, icon: 2 });
    },
    Close:
    {
        ByIndex: function (index) {
            window.parent.layer.close(index);
            return false;
        },
        ByAll: function () {
            try{
            window.parent.layer.closeAll();
            }catch(e){}
            return false;
        }
    }
};

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

$(window.parent.document).find("#" + GetQueryString("id")).remove();

function Loading() {
    if ($("#layer-table .center").length == 0) {
        $("#layer-table").html("<tr><td colspan='" + $("colgroup col").length + "' style='text-align:center;'>数据加载中...</td></tr>");
    }
};

var CRM = {
    Enter: function (id) {
        if (event.keyCode == 13) {
            $(id).click();
        }
    },
    ListID: function (id) { //获取id下所有class=select的val
        var array = new Array();
        window.parent.$(id).each(function () {
            array.push($(this).attr("id"));
            
        });
        return array + "";
    },
    ListValue: function (id) { //获取id下所有class=select的val
        var array = new Array();
        window.parent.$(id).each(function () {
            array.push($(this).val());

        });
        return array + "";
    },
    ListHTML: function (id) { //获取id下所有class=select的val
        var array = new Array();
        window.parent.$(id).each(function () {
            array.push($(this).html());

        });
        return array + "";
    },
    CListID: function (id) { //获取id下所有class=select的val
        var array = new Array();
        $(id).each(function () {
            array.push($(this).attr("id"));

        });
        return array + "";
    },
    CListValue: function (id) { //获取id下所有class=select的val
        var array = new Array();
        $(id).each(function () {
            array.push($(this).val());

        });
        return array + "";
    },
    CArrayID: function (id) { //获取id下所有class=select的val
        var array = new Array();
        $(id).each(function () {
            array.push($(this).attr("id"));
        });
        return array;
    },
    CheckValue: function (id) { //获取id下所有class=select的val
        var array = new Array();
        $(id + ":checked").each(function () {
            array.push($(this).val());

        });
        return array + "";
    }
};

var Validate = {
    IsMobile: function (str) {
        return new RegExp(/^^0?(13[0-9]|15[0-9]|18[0-9]|17[0-9]|14[57])[0-9]{8}$/).test(str)
    },
    IsCardID: function (str) {
        var arg1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
        var arg2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[A-Z])$/;
        if (str.match(arg1) == null && str.match(arg2) == null) {
            return false;
        }
        else {
            return true;
        }
    },
    IsQuote: function (str) {
        var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "{", "}", "[", "]", "(", ")");
        items.push(":", ";", "'", "|", "\\", "<", ">", "?", "/", "<<", ">>", "||", "//");
        items.push("admin", "administrators", "administrator", "管理员", "系统管理员");
        items.push("select", "delete", "update", "insert", "create", "drop", "alter", "trancate");
        str = str.toLowerCase();
        for (var i = 0; i < items.length; i++) {
            if (str.indexOf(items[i]) >= 0) {
                return true;
            }
        }
        return false;
    },
    IsUrl: function (str) {
        return str.match(/(http[s]?|ftp):\/\/[^\/\.]+?\..+\w$/i) != null;
    },
    IsPhone: function (str) {
        var regexp = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
        return regexp.test(str);
    },
    IsIP: function (str) {
        if (this.IsNull(str)) { return false; }
        if (/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g.test(str)) {
            if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) { return true; }
        }
        return false;
    },
    IsNull: function (str) {
        if (str == "") { return true; }
        return new RegExp("^[ ]+$").test(str);
    },
    IsEmail: function (str) {
        var reg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
        return reg.test(str);
    },
    IsSale: function (str) {
        var reg = /^(\d{1})(\.[0-9]{0,2})?$/;
        return reg.test(str);
    },
    IsChinese: function (str) {
        var reg = /^[\u4E00-\u9FFF]+$/;
        return reg.test(str);
    },
    IsDate: function (str) {//2012-12-12
        var reg = /^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$/;
        return reg.test(str);
    }
};
String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.LTrim = function () {
    return this.replace(/(^\s*)/g, "");
};
String.prototype.RTrim = function () {
    return this.replace(/(\s*$)/g, "");
};
String.prototype.ReplaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};
String.prototype.RHtml = function () {
    return this.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ");
};
String.prototype.DHtml = function () {
    return this.replace(/<[^>]+>/g, "");
};
String.prototype.DHtmlButImg = function () {
    return this.replace(/<(?!img).*?>/g, "");
};
String.prototype.Cut = function (length) {
    var len = this.length;
    return len > length ? this.substring(0, length) + '...' : this;
};
String.prototype.ToDate = function () {
    var date = new Date(this.replace(/-/g, "/"));
    return date.Format("yyyy-MM-dd");
};
String.prototype.ToDateTime = function () {
    return new Date(this.replace(/-/g, "/"));
};
String.prototype.ToTime = function () {
    if (this == "2015-01-01 00:00:00") {
        return "";
    }
    var date = new Date(this.replace(/-/g, "/"));
    return date.Format("yyyy-MM-dd hh:mm");
};
String.prototype.ToMinute = function () {
    if (this == "2015-01-01 00:00:00") {
        return "";
    }
    var date = new Date(this.replace(/-/g, "/"));
    return date.Format("MM月dd日 hh:mm");
};

String.prototype.GetLength = function () {
    return this.replace(/[^\x00-\xff]/g, 'xx').length;
};
Number.prototype.ToSex = function () {
    if (this == 1) {
        return "男";
    }else if (this == 2) {
        return "女";
    } else {
        return "未知";
    }
};
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.Remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

Array.prototype.RemoveAt = function (n) {
    if (n < 0)
    { return this; }
    else
    { return this.slice(0, n).concat(this.slice(n + 1, this.length)); }
};

Date.prototype.addDays = function (d) {
    this.setDate(this.getDate() + d);
};
Date.prototype.Format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(), //day 
        "h+": this.getHours(), //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
        "S": this.getMilliseconds() //millisecond 
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

function DateDiff(interval, date1, date2) {
    try {
        var objInterval = { 'Y': 1000 * 60 * 60 * 24 * 365, 'D': 1000 * 60 * 60 * 24, 'H': 1000 * 60 * 60, 'M': 1000 * 60, 'S': 1000, 'T': 1 };
        interval = interval.toUpperCase();
        var dt1 = Date.parse(date1.replace(/-/g, '/'));
        var dt2 = Date.parse(date2.replace(/-/g, '/'));
        return parseInt((dt2 - dt1) / eval('(objInterval.' + interval + ')'));
    }
    catch (e) {
        return e.message;
    }
};

/*上传控件*/
/*注：upload.setFileTypes('*.txt;*.doc;*.xls', '文档类型'); 的调用必须在Upload_File初始化之后，并且不能紧挨着初始化代码，要另写方法设置*/
function Upload_File(id, type, width, height, img, multiple) {
    var swfs;
    this.swfu = swfs;
    var file_types = "*.jpg;*.gif;*.png;*.jpeg;*.bmp";
    var file_width = 25;
    var file_height = 25;
    var file_img = "/system/img/adduploads.gif";
    var file_multiple = SWFUpload.BUTTON_ACTION.SELECT_FILE;
    var file_text = "";
    var allsize = 0;
    var hasload = 0;
    if (type) {
        file_types = type;
    }
    if (width) {
        file_width = width;
    }
    if (height) {
        file_height = height;
    }
    if (img) {
        file_img = img;
    }
    if (multiple) {
        file_multiple = SWFUpload.BUTTON_ACTION.SELECT_FILES;
    }
    var swfuOption = {//swfupload选项
        upload_url: "/tools/Upload.ashx", //接收上传的服务端url
        flash_url: "/system/js/swfupload.swf", //swfupload压缩包解压后swfupload.swf的url
        button_placeholder_id: id, //上传按钮占位符的id
        file_size_limit: "20MB", //用户可以选择的文件大小，有效的单位有B、KB、MB、GB，若无单位默认为KB
        file_upload_limit: 0,  // 上传文件的总个数
        file_queue_limit: 0,   // 每次能上传的文件个数
        file_types: file_types,
        custom_settings: {
            progressTarget: "fsUploadProgress",
            cancelButtonId: "btnCancel"
        },
        post_params: {
            "ASPSESSID": "<%=Session.SessionID %>"
        },
        multiple: true,
        button_width: file_width, //按钮宽度
        button_height: file_height, //按钮高度
        button_action: file_multiple,
        //button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,  //单选
        //button_action: SWFUpload.BUTTON_ACTION.SELECT_FILES, //多选
        button_image_url: file_img,
        button_text_style: '.button{color:#ffffff;font-size:12px;}',
        button_cursor: SWFUpload.CURSOR.HAND,
        upload_success_handler: uploadSuccess, //文件上传成功
        upload_complete_handler: uploadComplete,
        file_queued_handler: fileQueued,
        upload_progress_handler: uploadProgress,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialog,
        file_dialog_start_handler: prevDialog,
        file_dialog_complete_handler: afterDialog,
        debug: false
    };

    function uploadSuccess(file, serverData) {
        if (serverData.length > 0) {
            var json = serverData;
            if (this.handle == "upload_img") {
                serverData = serverData.split("*")[0];
                var src = serverData.substring(0, serverData.lastIndexOf(".")) + "_100" + serverData.substring(serverData.lastIndexOf("."),serverData.length);
                $("#img_panel").append('<div><img src="' + src + '"/><font id="' + json + '" onclick="RemoveFile(this)">&nbsp;&nbsp;×</font></div>');
            }
            if (this.handle == "upload_file") {
                serverData = serverData.split("*")[0];
                var src = serverData.substring(0, serverData.lastIndexOf(".")) + "_100" + serverData.substring(serverData.lastIndexOf("."),serverData.length);
                $("."+file.id).attr("id",json);
            }
            if (this.handle == "upload_product") {
                $("#upload_products").addClass("hidden");
                $("#upload_show").removeClass("hidden");
                json=$.parseJSON(json);
                $("#img_container").html("<img src='" + json[0] + "'/>");
            }
            if (this.handle == "upload_product1") {
                $("#upload_products1").addClass("hidden");
                $("#upload_show1").removeClass("hidden");
                json = $.parseJSON(json);
                $("#img_container1").html("<img src='" + json[0] + "'/>");
            }
            if (this.handle == "upload_product2") {
                $("#upload_products2").addClass("hidden");
                $("#upload_show2").removeClass("hidden");
                json = $.parseJSON(json);
                $("#img_container2").html("<img src='" + json[0] + "'/>");
            }
            if (this.handle == "upload_active") {
                serverData = serverData.split("*")[0];
                var src = serverData.substring(0, serverData.lastIndexOf(".")) + "_100" + serverData.substring(serverData.lastIndexOf("."), serverData.length);
                $("#upload_products").addClass("hidden");
                $("#upload_show").removeClass("hidden");
                $("#img_container").html("<img src='" + src + "'/>");
            }
        }
    };
    function afterDialog() {
        var option = {};
        var date = new Date();
        option.handle = this.handle;
        swfs.setPostParams(option);
        if (this.handle == "upload_img" || this.handle == "upload_file" || this.handle == "upload_product" || this.handle == "upload_product1" || this.handle == "upload_product2" || this.handle == "upload_active") {
            swfs.startUpload();
        }
       

    };
    function uploadComplete(file) {
        if (swfs.getStats().files_queued > 0) {  //没有这句，则只上传第一个文件
            swfs.startUpload();
        } else {
            if (this.handle == "upload_file") {
                $("#" + this.submitid).attr("filesuccess", "true");
                $("#" + this.submitid).click();
                allsize = 0;
                hasload = 0;
            }
        }
    };
    function fileQueued(file) {
        if (this.handle == "upload_img") {

        }
        if (this.handle == "upload_file") {
            $("#file_panel").append('<div>'+file.name.Cut(9)+'<font class="'+file.id+'" id="" onclick="RemoveFile(this)">&nbsp;&nbsp;×</font><div class="progress"></div><div class="percent">0%</div></div>');
            
        }
        if (this.handle == "upload_logo") {
            var index = LayerBox.Load("正在保存公司logo...");
        }
    };
    function uploadProgress(file, bytesLoaded) {
        try {
            if (this.handle == "upload_file") {
                var p = Math.floor(bytesLoaded / file.size * 100);
                    if (p >= 100) {
                        p = 100;
                    }
                    $("." + file.id).parent().find(".progress").css("width", (p+1)+"%");
                    $("." + file.id).parent().find(".percent").html(p + "%");
            }
        } catch (ex) {
            this.debug(ex);
        }
    };
    function fileQueueError(file, errorCode, message) {
        try {
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    alert("文件大小为0");
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    alert("您选择的文件大小为【" + GetSize(file.size) + "】，单个文件大小不能超过【" + swfs.settings.file_size_limit + "】");
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    break;
                default:
                    alert(message);
                    break;
            }

        } catch (ex) {
            this.debug(ex);
        }
    };
    function fileDialog() {

    };
    function prevDialog() {
        isdraged = true; //当弹出客户信息时，如果不加这句，在选完附件和图片后，弹层会消失
    };

   

    swfs = new SWFUpload(swfuOption);
    this.swfu = swfs;
};

function Re_Upload() {
    $(".upload_product").removeClass("hidden");
    $(".upload_show").addClass("hidden");
    $(".img_container img").attr("src", "");
};

function Re_Upload1() {
    $("#upload_products1").removeClass("hidden");
    $("#upload_show1").addClass("hidden");
    $("#img_container1 img").attr("src", "");
};

function Re_Upload2() {
    $("#upload_products2").removeClass("hidden");
    $("#upload_show2").addClass("hidden");
    $("#img_container2 img").attr("src", "");
};

function RemoveFile (o) {
        $(o).parent().remove();
};

function GetSign(act) {
    return md5("account=XinLian_MOBILE_CLIENT&act=" + act + "&key=365E6B86CE4E43A552G563078D5ADEFD");
};

function Request(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
};

function Delete_Table(o, ids, act) {
    var data = {};
    data.ids = ids;
    data.id = ids;
    data.act = act;
    data.sign = GetSign(data.act);
    LayerBox.Loading();
    Ajax.Post("/tools/Admin.ashx", data, function (r) {
        LayerBox.Close.ByAll();
        var json = $.parseJSON(r);
        if (json.state) {
            LayerBox.Success(json.msg);
            var currpage = 1;
            if ($(".layui-laypage-curr em").length > 0) {
                currpage = $(".layui-laypage-curr em")[1].innerHTML;
            }
            if ($("#layer-table tr").length > 1) {  //如果有一条以上数据，则只清空当前数据
                if ($(o).attr("flag") != "false") {
                    $(o).parent().parent().remove();
                }
            } else {                                //如果有一条数据，则回到第一页
                $(".layui-laypage").remove();
                Init_Pager(1);
            }

        }
        else {
            LayerBox.Error(json.msg);
        }
    });
};


function Pager(data, count, fun) {
    layui.use(['laytpl', 'laypage'], function () {
        $ = layui.jquery, form = layui.form(), laytpl = layui.laytpl, laypage = layui.laypage;
        var pages = parseInt((count - 1) / 20 + 1);
        laytpl($("#data-table").html()).render(data, function (html) {
            $("#layer-table").html(html);
            if (fun) { fun(); }
            form.render('checkbox');
            form.render('radio');
        });

        if ($(".layui-laypage").length == 0 && pages != 1 && pages != 0) {
            laypage({
                cont: 'layer-page',
                pages: pages,
                skip: true,
                jump: function (obj, first) {
                    $("<div style='float:left; line-height:30px; font-size:14px; text-align:right; padding-right:10px;'>共 " + count + " 条</div>").insertBefore(".layui-laypage-curr");
                    if (!first) {
                        Init_Pager(obj.curr);
                    }
                }
            });
        }
        if (pages == 1 || pages == 0) {
            $(".layer-page").html("<div style='float:right; line-height:40px; font-size:14px; text-align:right; padding-right:15px;'>共 " + count + " 条</div>");
        }
        if (count == 0) {
            $("#layer-table").html("<tr><td colspan='" + $("colgroup col").length + "' style='text-align:center;'>暂无数据</td></tr>");
        }
    });
};

function Pagers(data, count, fun) {
    layui.use(['laytpl', 'laypage'], function () {
        $ = layui.jquery, form = layui.form(), laytpl = layui.laytpl, laypage = layui.laypage;
        laytpl($("#data-table").html()).render(data, function (html) {
            $("#layer-table").html(html);
            if (fun) { fun(); }
            form.render('checkbox');
            form.render('radio');
        });
        if (count == 0) {
            $("#layer-table").html("<tr><td colspan='" + $("colgroup col").length + "' style='text-align:center;'>暂无数据</td></tr>");
        }
    });
};

function Data(data, count) {
    layui.use(['laytpl', 'laypage'], function () {
        $ = layui.jquery, form = layui.form(), laytpl = layui.laytpl, laypage = layui.laypage;
        var pages = parseInt((count - 1) / 20 + 1);
        laytpl(window.parent.$("#data-table").html()).render(data, function (html) {
            window.parent.$("#layer-table").html(html);
            form.render('checkbox');
            form.render('radio');
        });
        if (count == 0) {
            window.parent.$("#layer-table").html("<tr><td colspan='" + $("colgroup col").length + "' style='text-align:center;'>暂无数据</td></tr>");
        }
    });
};

function Search() {
    $(".layui-laypage").remove();
    Init_Pager(1);
};

String.prototype.ToDate = function () {
    if (this == "2015-01-01 00:00:00") {
        return "";
    }
    var date = new Date(this.replace(/-/g, "/"));
    return date.Format("yyyy-MM-dd");
};
String.prototype.ToDateTime = function () {
    return new Date(this.replace(/-/g, "/"));
};
String.prototype.ToTime = function () {
    if (this == "2015-01-01 00:00:00") {
        return "";
    }
    var date = new Date(this.replace(/-/g, "/"));
    return date.Format("yyyy-MM-dd hh:mm");
};

function State_Color(state) {
    if (state == 0) {
        return "red";
    } else if (state == 1) {
        return "red";
    } else if (state == 2) {
        return "blue";
    } else if (state == 3) {
        return "blue";
    }else if (state == 4) {
        return "green";
    }
};

//图片预览
function Img_Preview() {
    Mediabox.scanPage = function () {
        var links = $$(".imglist a").filter(function (el) {
            return el.rel && el.rel.test(/^lightbox/i);
        });
        window.parent.$$(links).mediabox({/* Put custom options here */
    }, null, function (el) {
        var rel0 = this.rel.replace(/[[]|]/gi, " ");
        var relsize = rel0.split(" ");
        return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
    });
};
window.addEvent("domready", Mediabox.scanPage);
};


function Init_Reply(sid, flag) {
    var data = {};
    data.act = "Find_Reply";
    data.sid = sid;
    data.flag = flag;
    data.sign = GetSign(data.act);
    Ajax.Post("/tools/API.ashx", data, function (r) {
        var json = $.parseJSON(r);
        var str = "";
        $.each(json.data.list, function (i, reply) {
            str += '<div class="orderreply">';
            str += '<div class="headimg"><img src="' + reply.HeadImg + '" /></div>';
            str += '<div class="info">';
            str += '<div class="top">';
            str += '<div class="realname">' + reply.RealName;
            if (flag == "examine") {
                str += ' - ' + Get_State(reply.State);
            }
            str += '</div>';
            str += '<div class="date">&nbsp;&nbsp;&nbsp;&nbsp;回复于 ' + reply.CreateDate.ToTime() + '</div>';
            str += '</div>';
            str += '<div class="middle">' + reply.Context + '</div>';
            str += '<div class="bottom">';
            str += '<div class="imglist">';
            $.each(reply.AnnexList, function (k, annex) {
                str += '<div class="img">';
                str += '<a href="' + annex.Img1000 + '" rel="lightbox[ostec]" title=""><img src="' + annex.Img100 + '"/></a>';
                str += '</div>';
            });
            str += '</div>';
            str += '</div>';
            str += '</div>';
            str += '</div>';
        });
        $("#replylist").html(str);
        Img_Preview();
    });
};

function Select_User(o) {
    var indexs = LayerBox.Loading();
    Ajax.Get("/system/page/oa/userselect.aspx?ids=" + $(o).attr("ids"), function (html) {
        LayerBox.Close.ByIndex(indexs);
        var index = window.parent.LayerBox.Dialog("选择用户", html, 605, 725, function (form) {
            Get_User();
            $(o).attr("ids", CRM.ListID("#layui-list .username"));
            LayerBox.Close.ByIndex(index);
        });
    });
};

function Select_Lower(o) {
    var indexs = LayerBox.Loading();
    Ajax.Get("/system/page/oa/lowerselect.aspx?ids=" + $(o).attr("ids"), function (html) {
        LayerBox.Close.ByIndex(indexs);
        var index = window.parent.LayerBox.Dialog("选择下级", html, 605, 725, function (form) {
            $(o).attr("ids", CRM.ListID("#layui-list .username"));
            $(o).val(CRM.ListHTML("#layui-list .username"));
            LayerBox.Close.ByIndex(index);
        });
    });
};

function Select_Sender(o) {
    var indexs = LayerBox.Loading();
    Ajax.Get("/system/page/oa/userselect.aspx?ids=" + $(o).attr("ids"), function (html) {
        LayerBox.Close.ByIndex(indexs);
        var index = window.parent.LayerBox.Dialog("选择员工", html, 605, 725, function (form) {
            if (window.parent.$("#layui-list .username").length > 1) {
                LayerBox.Error("请选择一个员工");
                return;
            }
            $(o).attr("ids", CRM.ListID("#layui-list .username"));
            $(o).val(CRM.ListHTML("#layui-list .username"));
            LayerBox.Close.ByIndex(index);
        });
    });
};

function Select_Examine(o) {
    if ($("#sendtype option:selected").attr("examineusers") == "") {
        var indexs = LayerBox.Loading();
        Ajax.Get("/system/page/oa/userselect.aspx?ids=" + $(o).attr("ids"), function (html) {
            LayerBox.Close.ByIndex(indexs);
            var index = window.parent.LayerBox.Dialog("选择审批人", html, 605, 725, function (form) {
                $(o).attr("ids", CRM.ListID("#layui-list .username"));
                $(o).val(CRM.ListHTML("#layui-list .username"));
                LayerBox.Close.ByIndex(index);
            });
        });
    }
};

function Get_User() {
    var str = '';
    $("#layui-list .username").each(function (i, info) {
        str += '<div class="layui-check-delete">';
        str += '<div class="check-names" id="' + $(info).attr("id") + '">' + $(info).html() + '</div>';
        str += '<div class="check-deletes" onclick="Remove_UserCheck(this)"><i class="layui-icon">&#x1006;</i></div>';
        str += '</div>';
    });
    $("#tousers").html(str);

};

function Remove_UserCheck(o) {
    $(o).parent().remove();
    $("#adduser").attr("ids", CRM.ListID("#tousers .check-names"));
};

function Select_ExamineUser(o) {
    var indexs = LayerBox.Loading();
    Ajax.Get("/system/page/oa/userselect.aspx?ids=" + $(o).attr("ids"), function (html) {
        LayerBox.Close.ByIndex(indexs);
        var index = window.parent.LayerBox.Dialog("选择用户", html, 605, 725, function (form) {
            Get_ExamineUser();
            $(o).attr("ids", CRM.ListID("#layui-list .username"));
            LayerBox.Close.ByIndex(index);
        });
    });
};

function Get_ExamineUser() {
    var str = '';
    $("#layui-list .username").each(function (i, info) {
        str += '<div class="layui-check-delete">';
        str += '<div class="check-names" id="' + $(info).attr("id") + '">' + $(info).html() + '</div>';
        str += '<div class="check-deletes" onclick="Remove_ExamineUserCheck(this)"><i class="layui-icon">&#x1006;</i></div>';
        str += '</div>';
    });
    $("#examineusers").html(str);

};

function Remove_ExamineUserCheck(o) {
    $(o).parent().remove();
    $("#addexamineuser").attr("ids", CRM.ListID("#examineusers .check-names"));
};


function Select_AssessmentUser(o) {
    var indexs = LayerBox.Loading();
    Ajax.Get("/system/page/oa/userselect.aspx?ids=" + $(o).attr("ids"), function (html) {
        LayerBox.Close.ByIndex(indexs);
        var index = window.parent.LayerBox.Dialog("选择用户", html, 605, 725, function (form) {
            if ($("#layui-list .username").length > 1) {
                LayerBox.Error("请选择一个员工");
                return;
            }
            $(o).attr("ids", CRM.ListID("#layui-list .username")).val($("#layui-list .username").html());
            LayerBox.Close.ByIndex(index);
        });
    });
};


function Show_Notice(id) {
    LayerBox.Loading();
    Ajax.Get("/system/page/oa/noticeinfo.aspx?id=" + id + "&v=" + Math.random(), function (html) {
        LayerBox.Close.ByAll();
        LayerBox.Detail("详情", html, 0, 0, null, function (form) {
        });
    });
};


function Show_Bbs(id) {
    LayerBox.Loading();
    Ajax.Get("/system/page/oa/bbsinfo.aspx?id=" + id + "&v=" + Math.random(), function (html) {
        LayerBox.Close.ByAll();
        LayerBox.Detail("问题详情", html, 0, 0, null, function (form) {
        });
    });
};


//下载文件
function DownLoads(path) {
    $("#download").attr("src", "/system/download.aspx?path=" + path);
};